package com.atguigu.java;

import org.junit.Test;

import java.util.Random;

/**
 * 通过反射创建对应的运行时类的对象
 */
public class NewInstance {
    @Test
    public void test1() throws Exception{
        Class<Person> clazz = Person.class;
        /**
         * newInstance:调用此方法，创建对应的运行时类的对象
         * 实际调用的无参构造器
         */
        Person obj = clazz.newInstance();
        System.out.println(obj);
    }

    @Test
    public void test2() throws Exception{
        int num = new Random().nextInt(3);  // 0,1,2
        String classPath = "";
        switch (num) {
            case 0:
                classPath = "java.util.Date";
                break;
            case 1:
                classPath = "java.lang.Object";
                break;
            case 2:
                classPath = "Person";
                break;
        }
        try {
            Object obj = getInstance(classPath);
            System.out.println(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 创建一个类的对象
    public Object getInstance(String classPath) throws Exception{
        Class clazz = Class.forName(classPath);
        return clazz.newInstance();
    }
}
